import DRCOutput
from Foundation import *
from AppKit import *
from PyObjCTools import NibClassBuilder, AppHelper
import threading

NibClassBuilder.extractClasses("DRC")

class DRCWindowController(NibClassBuilder.AutoBaseClass):
    FMWindowController = None
    
    _progressTotal = 0
    _progressComplete = 0
    _progressSemaphore = threading.Semaphore()

    def init( self ):
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "documentActivate:", u"SMUGFMDocumentActivate", None)
        return super(DRCWindowController, self).initWithWindowNibName_("DRC")

    def documentActivate_(self, notification):
        self.FMWindowController = notification.object()

    def startDRC_( self, sender ):
        document = self.FMWindowController.document()
        records = self.FMWindowController.selectedMeasurementRecords()
        recordCount = records.count()

        if recordCount == 0:
            NSBeginCriticalAlertSheet(u"Cannot perform DRC", u"OK", None, None, self.window(), None, None, None, 0, u"No records selected")
        else:
            # Launch a file open panel to allow the user to choose the directory which will contain the output files
            op = NSOpenPanel.openPanel()
            
            op.setAllowsMultipleSelection_(False)
            op.setCanChooseDirectories_(True)
            op.setCanChooseFiles_(False)
            op.setDelegate_(self)
            op.beginSheetForDirectory_file_modalForWindow_modalDelegate_didEndSelector_contextInfo_(None, None, self.window(), self, "openPanelDidEnd:returnCode:contextInfo:", 0)
    
    @AppHelper.endSheetMethod
    def openPanelDidEnd_returnCode_contextInfo_(self, panel, returnCode, context):
        """Handle the completion of the file open panel"""

        if not panel.filename() or returnCode != NSOKButton:
            return
        
        self.performSelector_withObject_afterDelay_("beginDRC:", panel.filename(), 0)
    
    def beginDRC_(self, directory):
        self._progressTotal = 0
        self._progressComplete = 0
        NSApp().beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_(self.progressSheet, self.window(), None, None, 0)
        self.progressBar.startAnimation_(self)
        document = self.FMWindowController.document()
        records = self.FMWindowController.selectedMeasurementRecords()
        for r in records:
            DRCOutput.performDRC( directory, r, self )
    
    def dismissSheet(self):
        self.progressSheet.orderOut_(self)
        NSApp().endSheet_(self.progressSheet)
        
    def drcStarted(self):
        """Notification that the DRC process has begun"""
        self._progressSemaphore.acquire()
        self._progressTotal += 1
        self.progressText.performSelectorOnMainThread_withObject_waitUntilDone_("setStringValue:", "Completed %d of %d correction files" % ( self._progressComplete, self._progressTotal ), True )
        self._progressSemaphore.release()
        
    def drcEnded(self):
        """Notification that the DRC process has ended"""
        self._progressSemaphore.acquire()
        self._progressComplete += 1
        self.progressText.performSelectorOnMainThread_withObject_waitUntilDone_("setStringValue:", "Completed %d of %d correction files" % ( self._progressComplete, self._progressTotal ), True )
        if self._progressTotal != 0:
            if self._progressTotal == self._progressComplete:
                self.progressBar.performSelectorOnMainThread_withObject_waitUntilDone_("stopAnimation:", self, True )
                self.performSelectorOnMainThread_withObject_waitUntilDone_("dismissSheet", None, True )

        self._progressSemaphore.release()
    
    def statusUpdate( self, message ):
        """Callback function used by the DRC thread.  We have to call 
        performSelectorOnMainThread to update the UI because DRC happens in a 
        separate thread."""
        self.textView.performSelectorOnMainThread_withObject_waitUntilDone_("insertText:", message, False )